<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib uri="http://shiro.apache.org/tags" prefix="shiro" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>


<title>商品管理 - 商品价格管理</title>

<link rel="stylesheet" href="${contextPath}/static/ace/components/_mod/jquery-ui/jquery-ui.css"/>
<link rel="stylesheet"
      href="${contextPath}/static/ace/components/bootstrap-datepicker/dist/css/bootstrap-datepicker3.css"/>
<link rel="stylesheet" href="${contextPath}/static/ace/components/_mod/jqgrid/ui.jqgrid.css"/>

<link rel="stylesheet" href="${contextPath}/static/XiaLaDuoXuan/css/public.css" media="all" />

<%--<jsp:include page="../../head.jsp"/>--%>
<script src="${contextPath}/static/statistics/js/vue.js"></script>
<!-- 数型插件 -->
<link href="${contextPath}/static/ztree/css/zTreeStyle.css" rel="stylesheet" />
<script type="text/javascript" src="${contextPath}/static/ztree/js/jquery.ztree.core-3.5.js"></script>
<script type="text/javascript" src="${contextPath}/static/ztree/js/jquery.ztree.excheck-3.5.js"></script>

<style type="text/css">
    .customBtn {
        line-height: 20px;
        margin-bottom: 3px;
    }

    .btnLine {
        margin-left: 1px;
        margin-top: 8px;
        margin-bottom: 2px;
    }

    @-webkit-keyframes bouncedelay {
        0%, 80%, 100% {
            -webkit-transform: scale(0.0)
        }
        40% {
            -webkit-transform: scale(1.0)
        }
    }

    @keyframes bouncedelay {
        0%, 80%, 100% {
            transform: scale(0.0);
            -webkit-transform: scale(0.0);
        }
        40% {
            transform: scale(1.0);
            -webkit-transform: scale(1.0);
        }
    }

    .autocomplete-suggestions {
        border: 1px solid #999;
        background: #FFF;
        overflow: auto;
    }

    .autocomplete-suggestion {
        padding: 2px 5px;
        white-space: nowrap;
        overflow: hidden;
    }

    .autocomplete-selected {
        background: #F0F0F0;
    }

    .autocomplete-suggestions strong {
        font-weight: normal;
        color: #3399FF;
    }

    @-moz-document url-prefix() {
        fieldset {
            display: table-cell;
        }
    }
	.ui-jqgrid .ui-priority-secondary{
		background: #d5effc;
	}

	.ui-jqgrid-sortable {
		text-align: center;
	}
	#jqgh_grid-table_cb{
		margin-left: 10px;
	}
</style>

<div class="row" id="app">
    <div class="row btnLine">
        <div class="button-len col-sm-12">
            <%--<shiro:hasPermission name="USER:ADD">--%>
                <%--<button type="button" class="btn btn-white btn-sm btn-purple customBtn" id="addCargo">--%>
                    <%--<i class="ace-icon fa fa-plus-circle purple"></i> 新增--%>
                <%--</button>--%>
            <%--</shiro:hasPermission>--%>

            <%--<shiro:hasPermission name="USER:EDIT">--%>
                <%--<button type="button" class="btn btn-white btn-info btn-sm customBtn" id="editShop">--%>
                    <%--<i class="ace-icon fa fa-pencil blue"></i> 修改--%>
                <%--</button>--%>
            <%--</shiro:hasPermission>--%>
			<%--<button type="button" class="btn btn-white btn-info btn-sm customBtn" v-on:click="priceType">--%>
				<%--修改折扣价--%>
			<%--</button>--%>
			<!-- 按钮触发模态框 -->
			<%--<button type="button" class="btn btn-white btn-info btn-sm customBtn" id="myModals" onclick="pageInit()">--%>
				<%--店铺价格下发--%>
			<%--</button>--%>
			<%--<button type="button" class="btn btn-white btn-info btn-sm customBtn" id="myModals" onclick="zoneHs()">--%>
				<%--区域价格下发--%>
			<%--</button>--%>
			<button type="button" class="btn btn-white btn-info btn-sm customBtn" id="myModals" onclick="zoneHss()">
				价格下发
			</button>

			<select class="input-sm" id="priceType">
				<option value="0">价格类型</option>
				<option value="1">原价格</option>
				<option :value="obj.code" v-for="(obj , index) in priceTypeArray">{{ obj.name }}</option>
			</select>
			<select class="input-sm" id="isExpInput">
				<option value="0">商品类型</option>
				<option :value="obj.typeId" v-for="(obj, index) in yanType1">
					{{ obj.typeName }}
				</option>

			</select>
			<select class="input-sm" id="isAuthInput">
				<option value="-1">商品大类</option>
				<option :value="obj.typeId" v-for="(obj, index) in yanType2">
					{{ obj.typeName }}
				</option>
			</select>

			<select class="input-sm" id="isAuthInput1">
				<option value="-1">商品中类</option>
				<option :value="obj.typeId" v-for="(obj, index) in yanType3">
					{{ obj.typeName }}
				</option>
			</select>

			<select class="input-sm" id="isAuthInput2">
				<option value="-1">商品小类</option>
				<option :value="obj.typeId" v-for="(obj, index) in yanType4">
					{{ obj.typeName }}
				</option>
			</select>

            <input class="input-sm" type="text" id="productCode" style="margin-left: 2px;"
                   placeholder="商品条码">
            <input class="input-sm" type="text" id="productName" style="margin-left: 2px;"
                   placeholder="商品名称">
            <button type="button" class="btn btn-sm btn-white btn-info search-len customBtn"
                    onclick="searchShop()">
                <i class="ace-icon fa fa-search orange"></i>搜索
            </button>
        </div>

		<div class="button-len col-sm-12 hide" id="commodityScreen" style="border-top: solid 1px #F5F5F5; margin-top: 5px;margin-bottom: 5px;">
			<div style="width: 100%;margin-top: 5px; margin-bottom: 5px;">
				<label style="">商品筛选</label><br/>
				<label style="margin-left: 25px">品牌：</label>
				<label class="checkbox-inline">
					<input type="checkbox" id="inlineCheckbox1" value="option1"> 选项 1
				</label>
				<label class="checkbox-inline">
					<input type="checkbox" id="inlineCheckbox2" value="option2"> 选项 2
				</label>
				<label class="checkbox-inline">
					<input type="checkbox" id="inlineCheckbox3" value="option3"> 选项 3
				</label>
			</div>
			<div style="width: 100%">
				<label style="">工业信息：</label>
				<select class="input-sm">
					<option>中国烟草总公司</option>
					<option>上海烟草集团公司</option>
					<option>贵州中烟工业有限责任公司</option>
				</select>
			</div>
		</div>
		<div class="button-len col-sm-12 hide" id="priceTypeArray" style="border-top: solid 1px #F5F5F5; margin-top: 5px;">
			<div class="button-len col-sm-12" style="margin-top: 5px; margin-bottom: 5px;">
				<label for="" style="margin-left: -13px;">折扣价：</label>
				<input class="input-sm" type="text" id="discount" style="margin-left: 2px;"
					   placeholder="折扣价">
				<button type="button" class="btn btn-white btn-info btn-sm customBtn btn-xs" type="button" id="submitPriceType">更新</button>
			</div>
		</div>
    </div>

    <div class="col-xs-12">

        <table id="grid-table"></table>

        <div id="grid-pager"></div>

    </div>

	<!-- 区域数型内容 -->
	<div id="authorizationInfoContentZone" class="hide">
		<div class="content_wrap">
			<div>
				<div style="border-bottom: solid 1px #000000;">
					<button type="button" class="btn btn-white btn-info btn-sm customBtn" onclick="getRadio(1)"> 店铺 </button>
					<button type="button" class="btn btn-white btn-info btn-sm customBtn" onclick="getRadio(2)"> 区域 </button>
				</div>
				<div class="" id="shop">
					<div class="button-len col-sm-12">
						<label for="" style="">店铺类型：</label>
						<select class="input-sm" id="shopType">
							<option value="">请选择</option>
							<option value="直营">直营</option>
							<option value="加盟">加盟</option>
						</select>

						<input class="input-sm" type="text" id="shopName" style="margin-left: 2px;" placeholder="店铺名称">
						<button type="button" class="btn btn-sm btn-white btn-info search-len customBtn" onclick="searchShopInfo()">
							<i class="ace-icon fa fa-search orange"></i>搜索
						</button>
					</div>

					<div class="button-len col-sm-12">
						<table id="grid-shop-table"></table>
						<div id="grid-shop-pager"></div>
					</div>
				</div>

				<div class="zTreeDemoBackground left hide" id="zone">
					<ul id="zoneDemo" class="ztree"></ul>
				</div>
			</div>
			<hr>
			<div>
				<label class="radio-inline">
					开始时间：<input class="input-sm" type="text" id="beginTime" style="margin-left: 2px;" placeholder="开始时间">
				</label>
				<label class="radio-inline">
					结束时间：<input class="input-sm" type="text" id="endTime" style="margin-left: 2px;" placeholder="结束时间">
				</label>
				<button type="button" class="btn btn-white btn-info btn-sm customBtn" id="" onclick="submitCtyShop()">
					下发
				</button>
			</div>
		</div>

		<%--<div>--%>
			<%--<button type="button" onclick="getZoneCodeBtn()" class="btn btn-success btn-sm" style="left: 240px;top: 450px;position: fixed;">确认</button>--%>
		<%--</div>--%>
	</div>
</div>


<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.mockjax.js"></script>
<script type="text/javascript" src="${contextPath}/static/statistics/js/jquery.autocomplete.js"></script>

<script type="text/javascript">

    var grid_shop_selector = "#grid-shop-table";
    var pager_shop_selector = "#grid-shop-pager";

    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";

    var laypage = layui.laypage,
        layer = layui.layer
    laydate = layui.laydate;

    var queryModel = {
        //分页参数
        page: '1',
        rows: '10',

        parentId: '0',
    }

	var app = new Vue({
		el: '#app',
		data: {
		    objcte: [],
            priceTypeArray: [],
            yanType1: [],
            yanType2: [],
            yanType3: [],
            yanType4: [],
            yanType5: []
		},
        methods: {
            submitCommodity: function () {
                submitCommodity()
            },
            addCommodity: function () {
                addCommodity()
            },
            priceType: function () {
                priceType()
            },
//            submitPriceType: function () {
//                submitPriceType()
//            }
		}
	})

    /**
     * 下啦联动数据绑定 开始代码
     * @type {{parentId: string}}
     */
    $('#isExpInput').change(function () {
        app.yanType2 = []
        app.yanType3 = []
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isExpInput option:selected").val();
        querySubProdType2()
    });

    $('#isAuthInput').change(function () {
        app.yanType3 = []
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isAuthInput option:selected").val();
        querySubProdType3()
    });

    $('#isAuthInput1').change(function () {
        app.yanType4 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = $("#isAuthInput1 option:selected").val();
        querySubProdType4()
    });

    $('#isAuthInput2').change(function () {
        app.yanType5 = []
        $("#commodityScreen").addClass("hide");
        queryModel.parentId = "";
        queryModel.typeId = $("#isAuthInput2 option:selected").val();
        querySubProdType5()
    });

    var querySubProdType1 = function () {
        getSubProdType1(queryModel)
    }
    var querySubProdType2 = function () {
        getSubProdType2(queryModel)
    }
    var querySubProdType3 = function () {
        getSubProdType3(queryModel)
    }
    var querySubProdType4 = function () {
        getSubProdType4(queryModel)
    }
    var querySubProdType5 = function () {
        getSubProdType5(queryModel)
    }


    var getSubProdType1 = function (queryModel) {
        // console.log(queryModel)

//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0){
                    layer.msg("查询没有数据")
                    return
                }
//                 console.log("dataArray: "+dataArray)
                app.yanType1 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType2 = function (queryModel) {
        console.log(queryModel)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0){
                    layer.msg("查询没有数据")
                    return
                }
                console.log("dataArray: "+dataArray)
                app.yanType2 = dataArray;

            },
            error: function (error) {
            }
        })
    }

    var getSubProdType3 = function (queryModel) {
        console.log(queryModel)
//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0){
                    layer.msg("查询没有数据")
                    return
                }
//                console.log("dataArray: "+dataArray)
                app.yanType3 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType4 = function (queryModel) {
        // console.log(queryModel)
//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getSubProdType',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0){
                    layer.msg("查询没有数据")
                    return
                }
//                console.log("dataArray: "+dataArray)
                app.yanType4 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    var getSubProdType5 = function (queryModel) {
        // console.log(queryModel)
//        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getProdProperty',
            type: 'post',
            data: queryModel,
            success: function (data) {
//                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;

                if (dataArray.length == 0){
                    layer.msg("查询没有数据")
                    return
                }
                $("#commodityScreen").removeClass("hide");
                console.log("dataArray: "+dataArray)
                app.yanType5 = dataArray;

            },
            error: function (error) {
//                layer.closeAll('loading')
            }
        })
    }

    querySubProdType1(queryModel);

    /**
     * 下啦联动数据绑定 结束代码
     */


    <%--//加载店铺信息--%>
    <%--var getShopInfo = function () {--%>
<%--//        console.log(queryModel)--%>
        <%--layer.load(1)--%>
        <%--$.ajax({--%>
            <%--url: '${contextPath}/ktProd/getShopListByPage',--%>
            <%--type: 'post',--%>
            <%--data: queryModel,--%>
            <%--success: function (data) {--%>
                <%--layer.closeAll('loading');--%>
                <%--if (data.success == false){--%>
                    <%--layer.msg("获取出错："+data.message)--%>
                    <%--return--%>
                <%--}--%>
                <%--var dataArray = data.recordList;--%>
<%--//                if (dataArray.length == 0){--%>
<%--//                    layer.msg("查询没有数据")--%>
<%--//                    return--%>
<%--//                }--%>

<%--//				dataArray = [--%>
<%--//                    {id: "1", productName: "测试店铺1"},--%>
<%--//                    {id: "2", productName: "测试店铺2"}--%>
<%--//                ]--%>
				<%--console.log(dataArray)--%>
				<%--app.objcte = dataArray;--%>
                <%--$('#myModal').modal('show');--%>
            <%--},--%>
            <%--error: function (error) {--%>
                <%--layer.closeAll('loading')--%>
            <%--}--%>
        <%--})--%>
    <%--};--%>


    $("#selectAll").click(function () {// 全选，为防止只生效一次的问题，用prop不用attr
        //获取是否选中
        var isChecked = $('#selectAll').prop('checked');
        console.log(isChecked)
		if (isChecked)
            $("input[name='colModel']").prop("checked", true);
        else
            $("input[name='colModel']").prop("checked",false);
    })


    //下发商品到店铺
	var submitShop = function () {
        console.log("下发商品到店铺")
		console.log(queryModel)
        layer.load(1)
        $.ajax({
			url: '${contextPath}/ktProd/saveProdPrice2Shop',
			type: 'post',
			data: queryModel,
            async : false,
			success: function (data) {
				layer.closeAll('loading');
				if (data.success == false){
				layer.msg("获取出错："+data.message)
				return
				}
				var dataArray = data.recordList;
//				if (dataArray.length == 0){
//					layer.msg("查询没有数据")
//					return
//				}
                layer.close(modalIndexZone)
                layer.msg("提示："+data.message)
	//        $('#myModal').modal('show');
                reload()
			},
			error: function (error) {
        		layer.closeAll('loading')
        	}
        })

    }

    var addCommodity = function () {
        $("#submitCommodity").addClass("hide");
        $("#alertTitle").html("价格管理 - 新增");
        $("#addCommodity").removeClass("hide");
        $('#myModal').modal('show');
    }

	//价格类型接口
	var priceType = function () {
        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/getProdPriceType',
            type: 'post',
//            data: queryModel,
            success: function (data) {
                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                var dataArray = data;
//                if (dataArray.length == 0){
//                    layer.msg("查询没有数据")
//                    return
//                }

//				console.log(dataArray)
                app.priceTypeArray = dataArray;
				$("#priceTypeArray").removeClass("hide");
            },
            error: function (error) {
                layer.closeAll('loading')
            }
        })
    }


    $('#priceType').change(function () {
        var priceType = $("#priceType").val();
        var discount = '';
        if (priceType == '1'){
            discount = '0.9';
		}else if (priceType == '2'){
            discount = '0.8';
		}
		$("#discount").val(discount);
		if (queryModel.typeId == ""){
            queryModel.typeId = queryModel.parentId;
		}

        queryModel.priceType = priceType;
		queryModel.discount = $("#discount").val();
    });


    //提交修改折扣价
    var submitPrice = function () {
        console.log('修改折扣价')
        console.log(queryModel)
        layer.load(1)
        $.ajax({
            url: '${contextPath}/ktProd/updateProdDiscountPriceByType',
            type: 'post',
            data: queryModel,
            async : false,
            success: function (data) {
                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                layer.msg("提示："+data.message)
                var dataArray = data;
                reload()
            },
            error: function (error) {
                layer.closeAll('loading')
            }
        })
    }

    $('#priceType').change(function () {
        var priceType = $("#priceType").val();
        var discount = '';
        if (priceType == '1'){
            discount = '0.9';
        }else if (priceType == '2'){
            discount = '0.8';
        }
        $("#discount").val(discount);
        if (queryModel.typeId == ""){
            queryModel.typeId = queryModel.parentId;
        }

        queryModel.priceType = priceType;
        queryModel.discount = $("#discount").val();
    });

    //更新商品价格
    var submitPriceType = function (ids) {
        var discount = $("#discount").val();
        var priceType = $("#priceType").val();
        if(priceType == "0"){
            layer.msg("提示：请选择价格类型")
			return
		}

        if(!discount){
            layer.msg("提示：折扣率不能为空")
            return
        }

        console.log(!queryModel.typeId)
        if (!queryModel.typeId){
            queryModel.typeId = queryModel.parentId;
        }
        queryModel.priceType = priceType;

        var productArray = [];
		console.log(discount)
        for (var i = 0; i < ids.length; i++){
            //获取对象数据
			var productData = {};
            var rowData = $(grid_selector).jqGrid('getRowData', ids[i]);
            var rtlPrice = rowData.rtlPrice;
            var discount_id = "#discount_"+rowData.productCode;
            var finalPrice_id = "#finalPrice_"+rowData.productCode;
            $(finalPrice_id).val((rtlPrice * discount).toFixed(2));
            $(discount_id).val(discount)
            productData.productCode = rowData.productCode;
            productData.discount = $(discount_id).val()
            productData.rtlPrice = $(finalPrice_id).val();
            productData.originalPrice = rowData.rtlPrice;
            productArray.push(productData);
		}

        queryModel.prodList = JSON.stringify(productArray);
        queryModel.properties = queryModel.parentId;
        submitPrice();
    }

    priceType()


	var discount = function (id,rtlPrice) {
		if(rtlPrice == "null"){
		    layer.msg("提示：本条商品数据异常")
			return
		}
        var discount_id = "#discount_"+id;
        var finalPrice_id = "#finalPrice_"+id;
        var discount = $(discount_id).val();
		$(finalPrice_id).val((rtlPrice * discount).toFixed(2));

    }
    var finalPrice = function (id,rtlPrice) {
        if(rtlPrice == "null"){
            layer.msg("提示：本条商品数据异常")
            return
        }
        var discount_id = "#discount_"+id;
        var finalPrice_id = "#finalPrice_"+id;
        var finalPrice = $(finalPrice_id).val();
        console.log($(finalPrice_id).val());
		$(discount_id).val((finalPrice / rtlPrice).toFixed(2))
    }

    var scripts = [null, "${contextPath}/static/ace/components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js", "${contextPath}/static/ace/components/jqGrid/js/jquery.jqGrid.js", "${contextPath}/static/ace/components/jqGrid/js/i18n/grid.locale-cn.js", "${contextPath}/static/layer/layer.js", null]
    $('.page-content-area').ace_ajax('loadScripts', scripts, function () {

        jQuery(function ($) {
            var parent_column = $(grid_selector).closest('[class*="col-"]');
            //resize to fit page size
            $(window).on('resize.jqGrid', function () {
                $(grid_selector).jqGrid('setGridWidth', parent_column.width());
            })

            //resize on sidebar collapse/expand
            $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
                if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
                    //setTimeout is for webkit only to give time for DOM changes and then redraw!!!
                    setTimeout(function () {
                        $(grid_selector).jqGrid('setGridWidth', parent_column.width());
                    }, 20);
                }
            })

            jQuery(grid_selector).jqGrid({
                //direction: "rtl",

                //subgrid options
                subGrid: false,
                <%--url: "${contextPath}/ktProd/getProdPrice",--%>
				url: "${contextPath}/ktProd/getProdTypePriceListByPage",
                //data: grid_data,
                datatype: "json",
                mtype: 'POST',
                height: 300,
                colNames: ['编号', '商品名称', '条码','状态','基础价(元)', '折扣率', '执行价(元)', '操作时间'],
                colModel: [
                    {name: 'id', index: 'id', width: 60, editable: true, key: true, hidden: true},
//                    {
//                        name: 'row',
//                        index: 'row',
//                        width: 90,
//                        editable: true,
//                        sortable: false,
//                        editrules: {required: true}
//                    },
                    {
                        name: 'productName',
                        index: 'productName',
                        width: 110,
                        editable: true,
                        sortable: false,
                        editrules: {required: true}
                    },
                    {
                        name: 'productCode',
                        index: 'productCode',
                        width: 90,
                        editable: true,
                        sortable: false,
                        editrules: {required: true}
                    },

                    {
                        name: 'state',
                        index: 'state',
                        width: 90,
                        editable: true,
                        sortable: false,
                        edittype: 'select',
                        formatter: function (v, x, r) {
                            return r['state'] == "1" ? "有效" : "无效";
                        },
                        editoptions: {value: "0:有效;1:无效"}
                    },
//                    {
//                        name: 'cstPrice',
//                        index: 'cstPrice',
//                        width: 90,
//                        editable: true,
//                        sortable: false,
//                        editrules: {required: true}
//                    },
                    {
                        name: 'rtlPrice',
                        index: 'rtlPrice',
                        width: 90,
                        editable: true,
                        sortable: false,
                        editrules: {required: true}
        			},
                    {
                        name: 'discount',
                        index: 'discount',
                        width: 90,
                        editable: true,
                        sortable: false,
                        editrules: {required: true},
                        formatter:function(cellvalue, options, rowObject) {
                            var rtlPrice = rowObject.rtlPrice;
                            var id = rowObject.productCode;
                            var discount = rowObject.discount;
                            if (!discount){
                                discount = 1
                            }
                            if (discount == 1){
                                discount = 0.9
                            }else if(discount == 2){
                                discount = 0.8
                            }
                            return ' <input type="text" id="discount_'+id+'" value="'+discount+'" onblur="discount('+id+','+rtlPrice+')" style="background-color: #ffffff;border:0;outline:0; margin-top: -16px;float: right; text-align: right;" />';
                        }
//                        edittype: 'select',
//                    	editoptions: {value: " :不选择; 1:元旦促销价; 2:国庆促销价"}
                    },
                    {
                        name: 'finalPrice',
                        index: 'finalPrice',
                        width: 60,
                        editable: true,
                        sortable: false,
                        editrules: {required: true},
                        formatter:function(cellvalue, options, rowObject) {
                            var rtlPrice = rowObject.rtlPrice;
                            var id = rowObject.productCode;
                            var finalPrice = rowObject.finalPrice;
                            if (!finalPrice){
                                finalPrice = 0
                            }
                            return ' <input type="text" id="finalPrice_'+id+'" value="'+finalPrice+'" onblur="finalPrice('+id+','+rtlPrice+')" style="background-color: #ffffff; border:0;outline:0; margin-top: -16px;float: right; text-align: right;" />';
                        }
                    },
                    {name: 'stateTime', index: 'stateTime', width: 150, editable: false}

                ],
                rownumbers: true, //自动行数
                viewrecords: true,
                rowNum: 2000,
                // rowList: [10, 20, 30],
                // pager: pager_selector,
                altRows: true,
                //toppager: true,

                multiselect: true,
                //multikey: "ctrlKey",
                multiboxonly: false,

                loadComplete: function () {
                    var table = this;
                    setTimeout(function () {
                        styleCheckbox(table);

                        updateActionIcons(table);
                        updatePagerIcons(table);
                        enableTooltips(table);
                    }, 0);
                },

                editurl: "${contextPath}/ktProd/saveProd",//nothing is saved
                caption: "商品价格管理",
                jsonReader: {
                    root: "recordList",
                    page: "currentPage",
                    total: "pageCount",
                    records: "recordCount"
                },

//                onSelectAll: function(rowids,statue){
//                    //函数里做自己的处理
//					queryModel.rowIds = rowids;
//                },
//                resetSelection: function(rowid){
//
//                    return(rowid)
//				}

            //,autowidth: true,


                /**
                 ,
                 grouping:true,
                 groupingView : {
				 groupField : ['name'],
				 groupDataSorted : true,
				 plusicon : 'fa fa-chevron-down bigger-110',
				 minusicon : 'fa fa-chevron-up bigger-110'
			},
                 caption: "Grouping"
                 */

            });

            $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size

			 
            /**
             * 下发价格
             */
            $("#myModals").click(function () {

                var discount_ = "#discount_";
                var finalPrice_ = "#finalPrice_";
                var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');  //获取选中的数据Id
                if(ids.length == 0){
                    layer.msg("提示：请选择商品！")
                    return
                }

                var typeId = queryModel.typeId;
                var priceType = $("#priceType").val()
                queryModel.finalPrice;

                if (priceType == '0'){
                    layer.msg("提示：价格类型！")
                    return
                }

                var productArray = [];
                for (var i = 0; i < ids.length; i++) {
                    //获取对象数据
                    var rowData = $(grid_selector).jqGrid('getRowData', ids[i]);

                    finalPrice_ = finalPrice_ + rowData.id;

                    var finalPrice = $(finalPrice_).val();
                    if (finalPrice == '0'){
                        layer.msg("提示：执行价不能为0！")
                        return
                    }
                    var productData = {}
//                    queryModel.finalPrice;

                    console.log(rowData)


					//获取input的value值
//                    var discount_Obj = $('#discount_' + rowData.productCode).find("#discount_"+rowData.productCode);
//                    var finalPrice_Obj = $('#finalPrice_' + rowData.productCode).find("#finalPrice_"+rowData.productCode);

                    var discount_id = "#discount_"+rowData.productCode;
                    var finalPrice_id = "#finalPrice_"+rowData.productCode;
                    var finalPrice = $(finalPrice_id).val();
                    productData.productCode = rowData.productCode;
					productData.discount = $(discount_id).val()
                    productData.rtlPrice = $(finalPrice_id).val();
                    productData.originalPrice = rowData.rtlPrice;
                    productArray.push(productData);

				}
//                console.log(JSON.stringify(productArray))

				queryModel.prodList = JSON.stringify(productArray);
//				console.log(queryModel)
                $("#addCommodity").addClass("hide");
                $("#alertTitle").html("价格下发 - 店铺选择");
                $("#submitCommodity").removeClass("hide");

                pageInit()
                $('#myModal').modal('show');

            });

            $("#submitPriceType").click(function () {
                var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');  //获取选中的数据Id
                if (ids.length == 0) {
                   	layer.msg("提示：请选择一条信息");
                    return;
                }
                submitPriceType(ids);
            });


            $("#editShopPrice").click(function () {
                var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
                if (!id) {
                    $.jgrid.info_dialog("提示：", "请选择一条信息");
                    return;
                }
                $(grid_selector).jqGrid("editGridRow", id, {
                    // edit record form
                    width: 500,
                    closeAfterEdit: true,
                    //editData :
                    recreateForm: true,
                    viewPagerButtons: false,
                    beforeShowForm: function (e) {
                      /*   var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                            .wrapInner('<div class="widget-header" />');
                        style_edit_form(form); */
                    },
                    afterShowForm: function (e) {
                        var form = $(e[0]);
                        //console.log(form)
                    },
                    afterSubmit: function (response, postdata) {
                        var result = eval('(' + response.responseText + ')');
                        ////console.log(result);
                        return [result.success, result.message, 0];
                    },
                    errorTextFormat: function (response) {
                        ////console.log("错误"+response.responseText);
                        //var result = response.responseText;
                        return "服务器异常，稍后再试";
                    }
                });
            });
            
            $("#editShop").click(function () {
                var id = $(grid_selector).jqGrid('getGridParam', 'selrow');
                if (!id) {
                    $.jgrid.info_dialog("提示：", "请选择一条信息");
                    return;
                }
                $(grid_selector).jqGrid("editGridRow", id, {
                    // edit record form
                    width: 500,
                    closeAfterEdit: true,
                    //editData :
                    recreateForm: true,
                    viewPagerButtons: false,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                            .wrapInner('<div class="widget-header" />');
                        style_edit_form(form);
                    },
                    afterShowForm: function (e) {
                        var form = $(e[0]);
                        //console.log(form)

                        $.ajax({
                            url: '${contextPath}/checking/selectQuXianNameToSelected',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#quXianName').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            //alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                                            //selectChannelNameToSelected(suggestion.value)
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        });

                        $.ajax({
                            url: '${contextPath}/checking/selectEmpNameToSelected?channelName=',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#empName').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            ////console.log('You selected: ' + suggestion.value + ', ' + suggestion.data);
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        });

                        $.ajax({
                            url: '${contextPath}/checking/selectChannelNameToSelected?quXianName=',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#realChannelName').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            //alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        });

                        $.ajax({
                            url: '${contextPath}/checking/selectMaterialCompanyToSelected',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#materialCompany').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            //alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        })

                    },
                    afterSubmit: function (response, postdata) {
                        var result = eval('(' + response.responseText + ')');
                        ////console.log(result);
                        return [result.success, result.message, 0];
                    },
                    errorTextFormat: function (response) {
                        ////console.log("错误"+response.responseText);
                        //var result = response.responseText;
                        return "服务器异常，稍后再试";
                    }
                });
            });
			
            $("#addCargo").click(function () {

                $(grid_selector).jqGrid("editGridRow", 'new', {
                    //new record form
                    //width: 700,
                    closeAfterAdd: true,
                    recreateForm: true,
                    viewPagerButtons: false,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                            .wrapInner('<div class="widget-header" />')
                        style_edit_form(form);
                    },
                    afterShowForm: function (e) {
                        var form = $(e[0]);
                        //console.log(form)

                        $.ajax({
                            url: '${contextPath}/checking/selectQuXianNameToSelected',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#quXianName').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            //alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                                            //selectChannelNameToSelected(suggestion.value)
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        });

                        $.ajax({
                            url: '${contextPath}/checking/selectEmpNameToSelected?channelName=',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#empName').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            ////console.log('You selected: ' + suggestion.value + ', ' + suggestion.data);
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        });

                        $.ajax({
                            url: '${contextPath}/checking/selectChannelNameToSelected?quXianName=',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#realChannelName').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            //alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        });

                        $.ajax({
                            url: '${contextPath}/checking/selectMaterialCompanyToSelected',
                            success: function (data) {
                                if (data.success) {
                                    var countries = data.data
                                    $('#materialCompany').autocomplete({
                                        lookup: countries,
                                        onSelect: function (suggestion) {
                                            //alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
                                        },
                                        width: 200,
                                        minChars: 0,
                                    });
                                }
                            }
                        })

                    },
                    afterSubmit: function (response, postdata) {
                        var result = eval('(' + response.responseText + ')');
                        ////console.log(result);
                        return [result.success, result.message, 0];
                    },
                    errorTextFormat: function (response) {
                        ////console.log("错误"+response.responseText);
                        //var result = response.responseText;
                        return "服务器异常，稍后再试";
                    }
                });

            })

            //enable search/filter toolbar
            //jQuery(grid_selector).jqGrid('filterToolbar',{defaultSearch:true,stringResult:true})
            //jQuery(grid_selector).filterToolbar({});


            //switch element when editing inline
            function aceSwitch(cellvalue, options, cell) {
                setTimeout(function () {
                    $(cell).find('input[type=checkbox]')
                        .addClass('ace ace-switch ace-switch-5')
                        .after('<span class="lbl"></span>');
                }, 0);
            }

            //enable datepicker
            function pickDate(cellvalue, options, cell) {
                setTimeout(function () {
                    $(cell).find('input[type=text]')
                        .datepicker({format: 'yyyy-mm-dd', autoclose: true});
                }, 0);
            }


            //navButtons
            jQuery(grid_selector).jqGrid('navGrid', pager_selector,
                { 	//navbar options
                    edit: false,
                    editicon: 'ace-icon fa fa-pencil blue',
                    add: false,
                    addicon: 'ace-icon fa fa-plus-circle purple',
                    del: false,
                    delicon: 'ace-icon fa fa-trash-o red',
                    search: false,
                    searchicon: 'ace-icon fa fa-search orange',
                    refresh: true,
                    refreshicon: 'ace-icon fa fa-refresh green',
                    view: false,
                    viewicon: 'ace-icon fa fa-search-plus grey',
                },
                {
                    //edit record form
                    //closeAfterEdit: true,
                    //width: 700,
                    recreateForm: true,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                        style_edit_form(form);
                    }
                },
                {
                    //new record form
                    //width: 700,
                    closeAfterAdd: true,
                    recreateForm: true,
                    viewPagerButtons: false,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar')
                            .wrapInner('<div class="widget-header" />')
                        style_edit_form(form);
                    }
                },
                {
                    //delete record form
                    recreateForm: true,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        if (form.data('styled')) return false;

                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                        style_delete_form(form);

                        form.data('styled', true);
                    },
                    onClick: function (e) {
                        //alert(1);
                    }
                },
                {
                    //search form
                    recreateForm: true,
                    afterShowSearch: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                        style_search_form(form);
                    },
                    afterRedraw: function () {
                        style_search_filters($(this));
                    }
                    ,
                    multipleSearch: true,
                    /**
                     multipleGroup:true,
                     showQuery: true
                     */
                },
                {
                    //view record form
                    recreateForm: true,
                    beforeShowForm: function (e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                    }
                }
            )


            function style_edit_form(form) {
                //enable datepicker on "sdate" field and switches for "stock" field
                //form.find('input[name=sdate]').datepicker({format:'yyyy-mm-dd' , autoclose:true})

                //form.find('input[name=stock]').addClass('ace ace-switch ace-switch-5').after('<span class="lbl"></span>');
                //don't wrap inside a label element, the checkbox value won't be submitted (POST'ed)
                //.addClass('ace ace-switch ace-switch-5').wrap('<label class="inline" />').after('<span class="lbl"></span>');


                //update buttons classes
                var buttons = form.next().find('.EditButton .fm-button');
                buttons.addClass('btn btn-sm').find('[class*="-icon"]').hide();//ui-icon, s-icon
                buttons.eq(0).addClass('btn-primary').prepend('<i class="ace-icon fa fa-check"></i>');
                buttons.eq(1).prepend('<i class="ace-icon fa fa-times"></i>')

                buttons = form.next().find('.navButton a');
                buttons.find('.ui-icon').hide();
                buttons.eq(0).append('<i class="ace-icon fa fa-chevron-left"></i>');
                buttons.eq(1).append('<i class="ace-icon fa fa-chevron-right"></i>');
            }

            function style_delete_form(form) {
                var buttons = form.next().find('.EditButton .fm-button');
                buttons.addClass('btn btn-sm btn-white btn-round').find('[class*="-icon"]').hide();//ui-icon, s-icon
                buttons.eq(0).addClass('btn-danger').prepend('<i class="ace-icon fa fa-trash-o"></i>');
                buttons.eq(1).addClass('btn-default').prepend('<i class="ace-icon fa fa-times"></i>')
            }

            function style_search_filters(form) {
                form.find('.delete-rule').val('X');
                form.find('.add-rule').addClass('btn btn-xs btn-primary');
                form.find('.add-group').addClass('btn btn-xs btn-success');
                form.find('.delete-group').addClass('btn btn-xs btn-danger');
            }

            function style_search_form(form) {
                var dialog = form.closest('.ui-jqdialog');
                var buttons = dialog.find('.EditTable')
                buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'ace-icon fa fa-retweet');
                buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'ace-icon fa fa-comment-o');
                buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'ace-icon fa fa-search');
            }

            function beforeDeleteCallback(e) {
                var form = $(e[0]);
                if (form.data('styled')) return false;

                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                style_delete_form(form);
                form.data('styled', true);
            }

            function beforeEditCallback(e) {
                var form = $(e[0]);
                form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                style_edit_form(form);
            }


            //it causes some flicker when reloading or navigating grid
            //it may be possible to have some custom formatter to do this as the grid is being created to prevent this
            //or go back to default browser checkbox styles for the grid
            function styleCheckbox(table) {
                /**
                 $(table).find('input:checkbox').addClass('ace')
                 .wrap('<label />')
                 .after('<span class="lbl align-top" />')


                 $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
                 .find('input.cbox[type=checkbox]').addClass('ace')
                 .wrap('<label />').after('<span class="lbl align-top" />');
                 */
            }


            //unlike navButtons icons, action icons in rows seem to be hard-coded
            //you can change them like this in here if you want
            function updateActionIcons(table) {
                /**
                 var replacement =
                 {
                     'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',
                     'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',
                     'ui-icon-disk' : 'ace-icon fa fa-check green',
                     'ui-icon-cancel' : 'ace-icon fa fa-times red'
                 };
                 $(table).find('.ui-pg-div span.ui-icon').each(function(){
				var icon = $(this);
				var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
				if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
			})
                 */
            }

            //replace icons with FontAwesome icons like above
            function updatePagerIcons(table) {
                var replacement =
                    {
                        'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                        'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                        'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                        'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
                    };
                $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                    var icon = $(this);
                    var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                    if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
                })
            }

            function enableTooltips(table) {
                $('.navtable .ui-pg-button').tooltip({container: 'body'});
                $(table).find('.ui-pg-div').tooltip({container: 'body'});
            }

            //var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

            $(document).one('ajaxloadstart.page', function (e) {
                $.jgrid.gridDestroy(grid_selector);
                $('.ui-jqdialog').remove();
            });
        });
    });
    var reload = function () {
//        $(grid_selector).jqGrid('clearGridData');  //清空表格
        $(grid_selector).jqGrid('setGridParam',{
            url:"${contextPath}/ktProd/getProdTypePriceListByPage",
            datatype:'json',
//                    postData:param,
            page:1
        }).trigger("reloadGrid"); //重新载入
    }


</script>
<script type="text/javascript">
    /**
     * 商品店铺
     */
    function searchShop() {

//        $('#myModal').modal('show');

		var parentId = $("#")
        var priceType = $("#priceType").val();
		var productCode = $("#productCode").val();
		var productName = $("#productName").val();
        //var parentDepartmentkey = $("#id_parentDepartmentkey_name").val();

//		if (priceType == "0"){
//		    layer.msg("提示：请选择价格类型！")
//			return
//		}
//        console.log(priceType);
		var filters = {
			"rules": [
				{
					"field": "productCode",
					"data": productCode
				}, {
					"field": "productName",
					"data": productName
				},
                {"field": "typeId", "data": ""},
	            {
	                "field": "priceType",
	                "data": priceType
	            }
			]
		};
         console.log(filters);

        jQuery("#grid-table").jqGrid('setGridParam', {
            postData: {
                "filters": JSON.stringify(filters) //"{'rules' : [{'field' : 'shopName','data' : "+shopName+"},{'field' : 'state','data' : "+state+"}]}"
            }
        }).trigger("reloadGrid");
    }

    /**
     * 搜索店铺
     */
    function searchShopInfo() {

//        $('#myModal').modal('show');


        var shopType = $("#shopType").val();
        var shopName = $("#shopName").val();
//        if (priceType == "0"){
//            layer.msg("提示：请选择价格类型！")
//            return
//        }
        console.log(shopName);
        var filters = {
            "rules": [
                {
                    "field": "shopName",
                    "data": shopName
                },
                {
                    "field": "shopType",
                    "data": shopType
                }
            ]
        };
        console.log(filters);

        jQuery("#grid-shop-table").jqGrid('setGridParam', {
            postData: {
                "filters": JSON.stringify(filters) //"{'rules' : [{'field' : 'shopName','data' : "+shopName+"},{'field' : 'state','data' : "+state+"}]}"
            }
        }).trigger("reloadGrid");
    }
</script>
<script>
	var type = 1;
    /**
     * 提交价格到店铺
     */
    var submitCtyShop = function () {
        if(type == 1) {
            var discount = $("#discount").val();
            var shopIdArray = [];
            var productArray = [];
            var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');  //获取选中的数据Id
            for (var i = 0; i < ids.length; i++){
                //获取对象数据
                var productData = {};
                var rowData = $(grid_selector).jqGrid('getRowData', ids[i]);
                var rtlPrice = rowData.rtlPrice;
                console.log(rtlPrice)

                var discount_id = "#discount_"+rowData.productCode;
                var finalPrice_id = "#finalPrice_"+rowData.productCode;
                $(finalPrice_id).val((rtlPrice * discount).toFixed(2));
                $(discount_id).val(discount)
                productData.productCode = rowData.productCode;
                productData.discount = $(discount_id).val()

                console.log(finalPrice_id)
                console.log($(finalPrice_id).val())

                productData.rtlPrice = $(finalPrice_id).val();
                productData.originalPrice = rowData.rtlPrice;

                console.log(productData)

                productArray.push(productData);
            }

            queryModel.prodList = JSON.stringify(productArray);

            var ids = $(grid_shop_selector).jqGrid('getGridParam', 'selarrrow');
            for (var i = 0; i < ids.length; i++) {
                var rowData = $(grid_shop_selector).jqGrid('getRowData', ids[i]);
                var idArray = {}
                idArray.shopId = rowData.shopId;
                shopIdArray.push(idArray)
            }
            if (ids.length == 0) {
                layer.msg("你还没有选择店铺！");
//            $("#smallTitle").removeClass("hide");
                return
            }

            var beginTime = $("#beginTime").val();
            var endTime = $("#endTime").val();

            if(!beginTime || !endTime){
                layer.msg("开始与结束时间不为空！")
                return;
            }

            $("#smallTitle").html("");
            $("#smallTitle").addClass("hide");
            queryModel.originalPrice = rowData.rtlPrice;
            queryModel.shopList = JSON.stringify(shopIdArray);
            queryModel.beginTime = beginTime;
            queryModel.endTime = endTime;
            console.log(queryModel)
            submitShop();
        }else {
            getZoneCodeBtn();
		}

    };

	// 加载店铺列表
    function pageInit(){
        jQuery(grid_shop_selector).jqGrid({
            subGrid: false,
            url : '${contextPath}/ktProd/getShopListByPage',
            datatype: "json",
            mtype: 'POST',
            height: 300,
            colNames: ['店铺编号', '店铺名称'],
            colModel: [
                {name: 'shopId', index: 'shopId', width: 200, editable: true, key: true},
//                    {
//                        name: 'row',
//                        index: 'row',
//                        width: 90,
//                        editable: true,
//                        sortable: false,
//                        editrules: {required: true}
//                    },
                {
                    name: 'shopName',
                    index: 'shopName',
                    width: 310,
                    editable: true,
                    sortable: false,
                    editrules: {required: true}
                }

            ],
//                rownumbers: true, //自动行数
            height:"100%",   //高度自适应
//			width: "100%",
            autowidth: true,  //宽度自适应
            viewrecords: true,
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: pager_shop_selector,
            altRows: true,
            //toppager: true,

            multiselect: true,
            //multikey: "ctrlKey",
            multiboxonly: true,

            loadComplete: function () {
                var table = this;
                setTimeout(function () {
                    styleCheckbox(table);

                    updateActionIcons(table);
                    updatePagerIcons(table);
                    enableTooltips(table);
                }, 0);
            },

            editurl: "${contextPath}/ktProd/getShopListByPage",//nothing is saved
//            caption: "店铺列表",
            jsonReader: {
                root: "recordList",
                page: "currentPage",
                total: "pageCount",
                records: "recordCount"
            },
//                onSelectAll: function(rowids,statue){
//                    //函数里做自己的处理
//					queryModel.rowIds = rowids;
//                },
//                resetSelection: function(rowid){
//
//                    return(rowid)
//				}

            //,autowidth: true,


            /**
             ,
             grouping:true,
             groupingView : {
				 groupField : ['name'],
				 groupDataSorted : true,
				 plusicon : 'fa fa-chevron-down bigger-110',
				 minusicon : 'fa fa-chevron-up bigger-110'
			},
             caption: "Grouping"
             */

        });
        //it causes some flicker when reloading or navigating grid
        //it may be possible to have some custom formatter to do this as the grid is being created to prevent this
        //or go back to default browser checkbox styles for the grid
        function styleCheckbox(table) {
            /**
             $(table).find('input:checkbox').addClass('ace')
             .wrap('<label />')
             .after('<span class="lbl align-top" />')


             $('.ui-jqgrid-labels th[id*="_cb"]:first-child')
             .find('input.cbox[type=checkbox]').addClass('ace')
             .wrap('<label />').after('<span class="lbl align-top" />');
             */
        }


        //unlike navButtons icons, action icons in rows seem to be hard-coded
        //you can change them like this in here if you want
        function updateActionIcons(table) {
            /**
             var replacement =
             {
                 'ui-ace-icon fa fa-pencil' : 'ace-icon fa fa-pencil blue',
                 'ui-ace-icon fa fa-trash-o' : 'ace-icon fa fa-trash-o red',
                 'ui-icon-disk' : 'ace-icon fa fa-check green',
                 'ui-icon-cancel' : 'ace-icon fa fa-times red'
             };
             $(table).find('.ui-pg-div span.ui-icon').each(function(){
				var icon = $(this);
				var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
				if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
			})
             */
        }

        //replace icons with FontAwesome icons like above
        function updatePagerIcons(table) {
            var replacement =
                {
                    'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
                    'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
                    'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
                    'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
                };
            $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
                var icon = $(this);
                var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

                if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
            })
        }

        function enableTooltips(table) {
            $('.navtable .ui-pg-button').tooltip({container: 'body'});
            $(table).find('.ui-pg-div').tooltip({container: 'body'});
        }

        //var selr = jQuery(grid_selector).jqGrid('getGridParam','selrow');

        $(document).one('ajaxloadstart.page', function (e) {
            $.jgrid.gridDestroy(grid_selector);
            $('.ui-jqdialog').remove();
        });

        $(window).triggerHandler('resize.jqGrid');//trigger window resize to make the grid get the correct size
    }

    //获取区域
    var getZone = function(){
        layer.load(1);
        var filters = {
            "rules": [
                // {"field": "parentId", "data": '0'},
                {"field": "state", "data": '1'},
            ]
        };
        var queryModels = {
            page: '1',
            rows: '10000',
            filters: JSON.stringify(filters),
        };

        console.log(queryModels)

        $.ajax({
            url : "${contextPath}/ktCommon/getZoneListByPage",
            type : "get",
            data : queryModels,
            dataType : "json",
            async : false,
            success : function(data) {
                layer.closeAll('loading');
                var dataArray = data.recordList;
                zoneArray = dataArray;
            },
            error : function () {
                layer.closeAll('loading');
                layer.msg("网络异常")
            }
        });

    }

    var zoneHs = function () {

        var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');  //获取选中的数据Id
        if(ids.length == 0){
            layer.msg("提示：请选择商品！")
            return
        }
        var priceType = $("#priceType").val()
        if (priceType == '0'){
            layer.msg("提示：价格类型！")
            return
        }

        var setting = {
            view: {
                dblClickExpand: false,
                showLine: true,
                selectedMulti: false,
            },
            check: {
                enable: true,
                chkStyle: "checkbox",
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: '',
                },
                key: {
                    name: 'zoneName'
                }
            },
            <%--async: {--%>
            <%--enable: false, // 设置 zTree是否开启异步加载模式  加载全部信息--%>
            <%--url: "${contextPath}/ktProd/getProdType", // Ajax 获取数据的 URL 地址--%>
            <%--autoParam: ["0"],    // 异步加载时自动提交父节点属性的参数,假设父节点 node = {id:1, name:"test"}，异步加载时，提交参数 zId=1--%>
            <%--//                dataFilter: queryModels,--%>
            <%--},--%>
            callback: { //回调函数
                /**
                 * event:鼠标事件
                 * treeId：树的容器id
                 * treeNode：当前点击的节点
                 */
                //双击
                // onDblClick: function (treeId, treeNode) {
                //     var treeObj = $.fn.zTree.getZTreeObj("zoneDemo");
                //     var node = treeObj.getSelectedNodes();//点击节点后 获取节点数据
                //     console.log(node[0].zoneName)
                //     $("#zoneName").val(node[0].zoneName);
                //     $("#zoneCode").val(node[0].zoneCode);
                //     layer.close(modalIndexZone)
                // }
            },
        }
        console.log(zoneArray)

        var zNodes =[];
        $.fn.zTree.init($("#zoneDemo"), setting, zoneArray);
        $("#authorizationInfoContentZone").removeClass("hide")
        modalIndexZone = layer.open({
            type: 1,
            title: '下发类型',
            closeBtn: 1,
            shadeClose: true,
            maxmin: true,
            area: ['570px','570px'],
            skin: 'yourclass',
            content: $("#authorizationInfoContentZone"),
            end: function () {
                $("#authorizationInfoContentZone").addClass("hide")
            }
        });
    }


    var zoneHss = function () {
        pageInit();
        var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');  //获取选中的数据Id
        if(ids.length == 0){
            layer.msg("提示：请选择商品！")
            return
        }
        var priceType = $("#priceType").val()
        if (priceType == '0'){
            layer.msg("提示：价格类型！")
            return
        }

        var setting = {
            view: {
                dblClickExpand: false,
                showLine: true,
                selectedMulti: false,
            },
            check: {
                enable: true,
                chkStyle: "checkbox",
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "parentId",
                    rootPId: '',
                },
                key: {
                    name: 'zoneName'
                }
            },
            <%--async: {--%>
            <%--enable: false, // 设置 zTree是否开启异步加载模式  加载全部信息--%>
            <%--url: "${contextPath}/ktProd/getProdType", // Ajax 获取数据的 URL 地址--%>
            <%--autoParam: ["0"],    // 异步加载时自动提交父节点属性的参数,假设父节点 node = {id:1, name:"test"}，异步加载时，提交参数 zId=1--%>
            <%--//                dataFilter: queryModels,--%>
            <%--},--%>
            callback: { //回调函数
                /**
                 * event:鼠标事件
                 * treeId：树的容器id
                 * treeNode：当前点击的节点
                 */
                //双击
                // onDblClick: function (treeId, treeNode) {
                //     var treeObj = $.fn.zTree.getZTreeObj("zoneDemo");
                //     var node = treeObj.getSelectedNodes();//点击节点后 获取节点数据
                //     console.log(node[0].zoneName)
                //     $("#zoneName").val(node[0].zoneName);
                //     $("#zoneCode").val(node[0].zoneCode);
                //     layer.close(modalIndexZone)
                // }
            },
        }
        console.log(zoneArray)

        var zNodes =[];
        $.fn.zTree.init($("#zoneDemo"), setting, zoneArray);
        $("#authorizationInfoContentZone").removeClass("hide")
        modalIndexZone = layer.open({
            type: 1,
            title: '区域',
            closeBtn: 1,
            shadeClose: true,
            maxmin: true,
            area: ['600px','500px'],
            skin: 'yourclass',
            content: $("#authorizationInfoContentZone"),
            end: function () {
                $("#authorizationInfoContentZone").addClass("hide")
            }
        });
    }

    var getZoneCodeBtn = function () {
        layer.load(1);
        var arrayData = {};
        var discount = $("#discount").val();
        var priceType = $("#priceType").val();
        if(priceType == "0"){
            layer.closeAll('loading');
            layer.msg("提示：请选择价格类型")
            return
        }

        if(!discount){
            layer.closeAll('loading');
            layer.msg("提示：折扣率不能为空")
            return
        }

        console.log(!queryModel.typeId)
        if (!queryModel.typeId){
            queryModel.typeId = queryModel.parentId;
        }
        queryModel.priceType = priceType;

        var productArray = [];
        console.log(discount)
        var ids = $(grid_selector).jqGrid('getGridParam', 'selarrrow');  //获取选中的数据Id
        for (var i = 0; i < ids.length; i++){
            //获取对象数据
            var productData = {};
            var rowData = $(grid_selector).jqGrid('getRowData', ids[i]);
            var rtlPrice = rowData.rtlPrice;
            var discount_id = "#discount_"+rowData.productCode;
            var finalPrice_id = "#finalPrice_"+rowData.productCode;
            $(finalPrice_id).val((rtlPrice * discount).toFixed(2));
            $(discount_id).val(discount)
            productData.productCode = rowData.productCode;
            productData.discount = $(discount_id).val()
            productData.rtlPrice = $(finalPrice_id).val();
            productData.originalPrice = rowData.rtlPrice;
            productArray.push(productData);
        }

        arrayData.prodList = JSON.stringify(productArray);
        arrayData.properties = queryModel.parentId;

		var zTree = $.fn.zTree.getZTreeObj("zoneDemo"),
			nodes = zTree.getChangeCheckedNodes();
		if (nodes.length == 0) {
            layer.closeAll('loading');
			layer.msg("请选择区域")
			return
		}
        var checkedZoneCode = [];//用来存储被选择的节点
        for (var i=0, l=nodes.length; i<l; i++) {
            if(nodes[i].checked && nodes[i].isParent!=true) {
                checkedZoneCode = checkedZoneCode.concat(nodes[i].id);
            }
        }
        arrayData.checkedZoneCode = checkedZoneCode.join(',');

        var beginTime = $("#beginTime").val();
        var endTime = $("#endTime").val();

        if(!beginTime || !endTime){
            layer.msg("开始与结束时间不为空！")
            return;
        }
        arrayData.beginTime = beginTime;
        arrayData.endTime = endTime;

        console.log(arrayData)

        $.ajax({
            url : "${contextPath}/ktProd/saveProdPrice2Shop",
            type : "post",
            dataType : "json",
            async : false,
            data : arrayData,
            success : function(data) {
                layer.closeAll('loading');
                if (data.success == false){
                    layer.msg("获取出错："+data.message)
                    return
                }
                layer.close(modalIndexZone)
                layer.msg("提示："+data.message)
                reload()

            },
            error : function () {
                layer.closeAll('loading');
                layer.msg("网络异常")
            }
        })
    }

    var getRadio = function (val) {
        console.log(val);
        type = val;
        if(val == 1){
            $("#shop").removeClass("hide");
            $("#zone").addClass("hide");
            $("#type").addClass("hide");
            return;
        }
        if(val == 2){
            $("#zone").removeClass("hide");
            $("#shop").addClass("hide");
            $("#type").addClass("hide");
            return;
        }
        if(val == 3){
            $("#type").removeClass("hide");
            $("#zone").addClass("hide");
            $("#shop").addClass("hide");
            return;
        }
    }

    //     $('#beginTime').datetimepicker({
//         minView: "month", //选择日期后，不会再跳转去选择时分秒
//         language: 'zh-CN',  //汉化
//         weekStart: 1,
//         todayBtn: 1,
//         autoclose: 1,
//         todayHighlight: 1,
// //        startView: 2,
//         forceParse: 0,
//         minView: 2,
//         showMeridian: 1,
//         format: "yyyy-mm-dd hh:mm:ss", //选择日期后，文本框显示的日期格式
//         autoclose:true, //选择日期后自动关闭
//         minuteStep:1,
// //        startDate:new Date(),
//     });

    $(function () {
        getZone();
    })
</script>

<!-- 时间控件 -->
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.min.js"></script>
<script src="${contextPath}/static/statistics/js/bootstrap-datetimepicker.zh-CN.js"></script>
<script type="text/javascript">
    $('#beginTime').datetimepicker({
        minView: "month", //选择日期后，不会再跳转去选择时分秒
        language: 'zh-CN',  //汉化
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
//        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyy-MM-dd hh:mm:ss", //选择日期后，文本框显示的日期格式
        autoclose:true, //选择日期后自动关闭
        minuteStep:1,
//        startDate:new Date(),
    });
    $('#endTime').datetimepicker({
        minView: "month", //选择日期后，不会再跳转去选择时分秒
        language: 'zh-CN',  //汉化
        weekStart: 1,
        todayBtn: 1,
        autoclose: 1,
        todayHighlight: 1,
//        startView: 2,
        forceParse: 0,
        minView: 2,
        showMeridian: 1,
        format: "yyyy-MM-dd hh:mm:ss", //选择日期后，文本框显示的日期格式
        autoclose:true, //选择日期后自动关闭
        minuteStep:1,
//        startDate:new Date(),
    });
</script>
<link rel="stylesheet" href="${contextPath}/static/XiaLaDuoXuan/css/public.css" media="all" />
<script type="text/javascript" src="${contextPath}/static/XiaLaDuoXuan/selectMultiple.js"></script>
